<template>
  <div v-if="jsonData.list" v-loading="loading">
    <fm-generate-form :data="jsonData" :remote="remoteFuncs" ref="generateForm" @on-change="onChange">
    </fm-generate-form>
    <slot name="quill-editor"></slot>
    <slot name="email-btn"></slot>
  </div>
</template>

<script>
import config from '@/utils/config'
import { GlobalTimeformat } from '@/utils/common'
import store from '@/store'
import Cookies from 'js-cookie'
import getDataset from './form-fuction'
import moment from 'moment'
export default {
  props: {
    userformData: {
      type: Object,
      default: () => {
        return {
          formTitle: null,
          formCode: null,
          id: null
        }
      }
    },
    visible: {
      type: Boolean,
      default: () => {
        return false
      }
    }
  },
  data () {
    return {
      loading: false,
      jsonData: {},
      dynamicData: {
        radio_options: []
      },
      remoteFuncs: {
        func_options (resolve) {
          getDataset.clientList().then(({ data: res }) => {
            const options = res.data
            resolve(options)
          })
            .catch((e) => {

            })
        },
        clientList (resolve) {
          getDataset.timeZoneList().then(({ data: res }) => {
            const options = res.data
            resolve(options)
          })
            .catch((e) => {

            })
        }
      },
      dataContent: {}
    }
  },
  watch: {
    userformData: {
      handler: function (val) {
        if (val.formCode) {
          this.id = this.userformData.id
          if (this.$route.path === '/userForm') this.getformData()
          else this.getJsonData()
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    onChange (field, value, data) {
      this.$emit('on-change',field, value, data)
    },
    hasPerViewFormList (roleIds) {
      let list = 0

      return list
    },
    hasPerViewFormData () {

    },
    resetFormMaking () {
      if (this.$refs.generateForm) {
        this.$refs.generateForm.reset()
      }
    },
    getJsonData () {
      this.id = this.userformData.id
      let formCode = this.userformData.formCode
      const params = { formCode: formCode }
      if (!this.id) {
        this.$interface.reports.getjsonDataApi(params).then(({ data: res }) => {
          if (res.code !== 0) {
            this.$emit('closeLoading')
            return this.$message.error(res.msg)
          }
          var temp = this.apiConfig(res.data.formSchema)
          this.$emit('jsonData', temp)
          this.jsonData = temp
          this.$nextTick(() => {
            this.$refs.generateForm.refresh()
          })
          this.formVersion = res.data.formVersion
          this.$forceUpdate()
          this.$emit('closeLoading')
        }).catch(() => {
          this.$emit('closeLoading')
        })
      }
      if (this.id) {
        const params = { id: this.id }
        this.$interface.reports.getjsonDataApiFromId(params).then(({ data: res }) => { // getFormDataApi
          if (res.code !== 0) {
            this.$emit('closeLoading')
            return this.$message.error(res.msg)
          }
          var temp = this.apiConfig(res.data.form.formSchema)
          this.$emit('jsonData', temp)
          this.jsonData = temp
          this.$nextTick(() => {
            this.$refs.generateForm.refresh()
          })
          this.$emit('formTitle', res.data.form.formTitle)
          this.$forceUpdate()
          this.formVersion = res.data.form.formVersion
          this.$emit('setSignature',res.data.data.dataContent)
          this.$nextTick(() => {
            this.$refs.generateForm.setData(res.data.data.dataContent)
          })
          this.$emit('closeLoading')
        }).catch(() => {
          this.$emit('closeLoading')
        })
      } else {
        this.$emit('closeLoading')
      }
    },
    getformData () { // web/reports/sys/share/valid
      let _self = this
      let params = {
        // userformData: _self.userformData.formCodeformCode
        resourceId: _self.userformData.formCode ? _self.userformData.formCode : null,
        userId: _self.$store.state.user.id ? _self.$store.state.user.id : null
      }
      _self.$interface.reports.getFormDataApiValid(params).then(({ data: res }) => {
        // if (res.code !== 0) {
        //   _self.$emit('closeLoading')
        //   return _self.$message.error(res.msg)
        // }
        _self.$emit('formTitle', res.data.formTitle)
        if (res.code === 10049) {
          if (_self.$store.state.user.id) {
            return _self.$notify({
              title: 'ERROR',
              message: 'Permission verification failed',
              duration: 0,
              iconClass: 'el-icon-error'
            })
          } else {
            _self.$router.replace({
              name: 'login'
            })
          }
        }
        if (res.code === 10048) {
          return _self.$notify({
            title: 'ERROR',
            message: 'Resource out of date',
            duration: 0,
            iconClass: 'el-icon-error'
          })
        }
        if (res.code === 404) {
          return _self.$notify({
            title: 'ERROR',
            message: 'Resource not found',
            duration: 0,
            iconClass: 'el-icon-error'
          })
        }

        if (res.code === 0 && _self.$route.query.formCode && _self.$route.query.id) _self.getJsonData()
        else if (res.code === 0 && _self.$route.query.formCode && !_self.$route.query.id) {
          var temp = _self.apiConfig(res.data.formSchema)
          _self.jsonData = temp
          _self.formVersion = res.data.formVersion
          if (_self.$route.query && _self.$route.query.score) {
            _self.$nextTick(() => {
              try {
                let isUsed = false
                for (var i = 10; i >= 0; i--) {
                  if (_self.$route.query.score.includes(i)) {
                    isUsed = true
                    _self.$route.query.score = i
                    break
                  }
                }
                if (!isUsed) {
                  this.$alert('This link is incorrect, please use the correct link', 'Warning', {
                    confirmButtonText: 'Close',
                    callback: action => {
                      window.location.href = 'about:blank'
                      window.close()
                    }
                  })
                }
              } catch (error) {

              }
              _self.$refs.generateForm.setData({ ..._self.$route.query, createTime: moment().utc() })
              // eslint-disable-next-line
              if (_self.$route.query.autoSubmit == 'true') {
                _self.addOrUpdateFormData('isNPS')
              }
            })
          }
          _self.$emit('closeLoading')
          _self.$forceUpdate()
        }

        // _self.jsonData = res.data.form.formSchema
        // _self.$forceUpdate()
        // _self.formVersion = res.data.form.formVersion
      }).catch((e) => {
        _self.loading = false
      })
    },
    apiConfig (res) {
      if (res.config.dataSource) {
        res.config.dataSource.forEach(item => {
          item.headers.tenantCode = Cookies.get('tenant_code') || ''
          item.headers.timezoneOffset = store.state.user.timezoneOffset ? store.state.user.timezoneOffset : ''
          item.headers.token = Cookies.get('token') || ''
        })
      }
      return res
    },
    addOrUpdateFormData (value,javaMailProperties_mail_smtp_signing,isEdit) {
      return new Promise((resolve, reject) => {
        let formCode = this.userformData.formCode
        this.specialForm(formCode, value)
        this.$refs.generateForm.getData().then((val) => {
          if(isEdit) {
            val.status = false
          }
          if(javaMailProperties_mail_smtp_signing) {
            val.javaMailProperties_mail_smtp_signing = javaMailProperties_mail_smtp_signing
          }
          var params
          if (this.id) {
            params = { id: this.id, dataContent: val }
          } else {
            params = { formCode: formCode, formVersion: this.formVersion, dataContent: val }
          }
          this.loading = true
          this.$interface.reports.addOrUpdateFormDataApi(params).then(({ data: res }) => {
            let url = window.location.origin + `/userForm?id=${res.data.id}&formCode=${res.data.formCode}`
            if (res.code !== 0) {
              this.loading = false
              return this.$message.error(res.msg)
            }
            this.loading = false
            this.$message.success('Submitted successfully')
            this.$parent.visible = false
            this.$emit('envent',res.data)
            this.$emit('updateDataId', res.data.id)
            resolve(res.data.id)
            // return this.$notify({
            //   title: 'ERROR',
            //   message: 'Submitted successfully',
            //   duration: 0,
            //   iconClass: 'el-icon-success'
            // })
            if (this.userformData.formCode && this.userformData.id) this.getJsonData()
            if (this.$route.path === '/userForm' && this.userformData.formCode && !this.userformData.id) {
              if (value !== 'isNPS') {
                this.$refs.generateForm.reset()
              }
              return this.$notify({
                title: 'Submitted successfully',
                dangerouslyUseHTMLString: true,
                message: `<span style={text-align: left;}>View submission results</span>  <a href="${url}" target="_blank">${url}</a>`,
                iconClass: 'el-icon-success',
                duration: 0,
                customClass: 'submittUrl'
              })
            }
          }).catch(() => {
            this.loading = false
            reject()
          })
        })
      })
    },
    specialForm (formCode, key) {
      if (formCode === config.grantAccessFormCode) {
        const createTimestamp = new Date().getTime()
        const value = this.$refs.generateForm.getValues()
        let num = 0
        if (value.unit === 'Hours') {
          num = 1000 * 60 * 60
        }
        if (value.unit === 'Days') {
          num = 1000 * 60 * 60 * 24
        }
        const expireTimestamp = key === 'revokeAccess' ? 100 : createTimestamp + (Number(value.time) * num)
        const formatDate = GlobalTimeformat(expireTimestamp, 'HH:mm', this.$store.state.user.timeFormat || 'YYYY-MM-DD')
        this.$refs.generateForm.setData({
          createTimestamp,
          expireTimestamp,
          text2: `Granted access will expire on ${formatDate}`
        })
      }
    }
  }
}
</script>
<style lang="scss">
.toolong .el-form-item__content {
  overflow: scroll !important;
}

.submittUrl p {
  word-wrap: break-word;
  word-break: break-all;
  overflow: hidden;

  a {
    color: $--theme-color;
  }
}
</style>
